package com.web.expspringboot.service.hustImpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.web.expspringboot.entity.TmpInfo;
import com.web.expspringboot.entity.UserSt;
import com.web.expspringboot.mapper.UserMapper;
import com.web.expspringboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Service
@Profile("hust")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper um;

    @Autowired
    HttpServletRequest request;

    //api 获取验证码
    @Override
    public boolean getPhoneCode(String phoneNum, int mode) {
        //生成6位验证码
        String verificationCode = generateVerificationCode(6);
        // 创建一个 VerificationInfo 对象并设置手机号、验证码和模式
        TmpInfo info = new TmpInfo();
        info.setPhoneNumber(phoneNum);
        info.setVerificationCode(verificationCode);
        info.setMode(phoneNum+mode);
        // 将 VerificationInfo 对象转换为 JSON 字符串
        String jsonInfo = JSON.toJSONString(info);

        if (sendCode(phoneNum,verificationCode)){
            try {
                // 连接 Redis
                Jedis jedis = new Jedis("localhost", 6379);
                // 将信息存储到 Redis 中，使用mode作为键
                jedis.setex(info.getMode(), 120, jsonInfo);
                // 关闭 Redis 连接
                jedis.close();
                return true;
            }catch (Exception e){
                System.out.println("获取验证码时服务器调取redis失败，错误："+e);
            }
        }
        return false;
    }
    //生成随机验证码
    public static String generateVerificationCode(int length) {
        String numbers = "0123456789"; // 可供选择的字符集合

        Random random = new Random();
        StringBuilder code = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(numbers.length());
            code.append(numbers.charAt(randomIndex));
        }
        System.out.println("生成随机验证码"+code.toString());
        return code.toString();
    }
    //发送验证码
    private boolean sendCode(String phoneNum, String code){
        String appcode = " 3d65f8435f184453bc65d9269585e979";

        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phoneNum);
        querys.put("param", "**code**:"+code+",**minute**:1");
        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");

        String authorization = "APPCODE " + appcode;

        try {
            String response = sendSms(authorization,querys);
            //获取response的code
            JSONObject jsonObject = JSONObject.parseObject(response);
            String codeValue = jsonObject.getString("code");
            if (codeValue.equals("0")){
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            System.out.println("发送验证码失败，错误"+e);
        }
        return false;
    }

    //接口失效
    public String sendSms(String authorization, Map<String, String> request) {
        /*String baseUrl = "https://gyytz.market.alicloudapi.com/sms/smsSend";
        // 构建URL并附加查询参数
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(baseUrl);
        request.forEach(uriBuilder::queryParam);
        String urlWithParams = uriBuilder.toUriString();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", authorization);

        // 创建RestTemplate实例
        RestTemplate restTemplate = new RestTemplate();

        // 创建HttpEntity
        HttpEntity<String> entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(urlWithParams, HttpMethod.POST, entity, String.class);

        return response.getBody();*/
        return "{code:0}";
    }

    //获取redis里的验证码
    public static String checkCode(String phoneNum, int mode){
        Jedis jedis = new Jedis("localhost", 6379);
        String code = "none"; // 默认返回值

        // 获取存储的 JSON 字符串
        String jsonInfo = jedis.get(phoneNum+mode);

        if (jsonInfo != null) {
            JSONObject jsonObject = JSON.parseObject(jsonInfo);
            code = jsonObject.getString("verificationCode");
        }

        jedis.close();
        return code;
    }

    //登录
    @Override
    public int signInCheck(String phoneNum, String password) {
        HttpSession session = request.getSession();
        UserSt user = um.selectUserByPhoneNum(phoneNum);
        if (user==null){
            return 1;
        }
        if (user.getUserBanned()==1){
            return 3;
        }
        if (user.getUserPassword().equals(password)){
            session.setAttribute("user", user);
            return 0;
        }else {
            return 2;
        }
    }

    //注册
    @Override
    public int signUp(String phoneNum, String code, String password) {
        UserSt user = um.selectUserByPhoneNum(phoneNum);
        if (user != null){
            return 1;
        }
        if (!checkCode(phoneNum, 0).equals(code)){
            return 2;
        }else {
            //插入新用户
            UserSt newUser = new UserSt();
            newUser.setUserAccount(phoneNum);
            newUser.setUserPassword(password);
            newUser.setUserName("匿名用户");
            um.insertUser(newUser);
            return 0;
        }
    }

    //更改密码
    @Override
    public int resetPassword(String phoneNum, String code, String newPassword) {
        HttpSession session = request.getSession();
        UserSt user = um.selectUserByPhoneNum(phoneNum);
        if (user == null){
            return 1;
        }
        if (!checkCode(phoneNum, 1).equals(code)){
            return 2;
        }else{
            user.setUserPassword(newPassword);
            um.updateUser(user);
            session.setAttribute("user", user);
            return 0;
        }
    }

    //返回是否是管理员
    @Override
    public boolean getIsManager(String phoneNum) {
        UserSt user = um.selectUserByPhoneNum(phoneNum);
        if (user == null){
            return false;
        }
        return user.getIsManager() == 1;
    }

    //获取所有用户
    @Override
    public List<UserSt> getAllUser() {
        return um.getAllUser();
    }

    //更新一条用户信息
    @Override
    public boolean updateOneUser(UserSt user) {
        HttpSession session = request.getSession();
        if (um.updateUser(user)){
            session.setAttribute("user", user);
            return true;
        }
        return false;
    }

    //获取session中的用户id，用于简单鉴权
    @Override
    public Long getSessionUserId() {
        HttpSession session = request.getSession();
        UserSt user = (UserSt) session.getAttribute("user");
        if (user == null){
            return null;
        }
        return user.getUserId();
    }

    @Override
    public boolean logout() {
        HttpSession session = request.getSession();
        if (session.getAttribute("user") == null){
            //未登录
            return false;
        }
        session.removeAttribute("user");
        return true;
    }

}

